package com.example.myapplication;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.myapplication.model.MedicalRecordFetcher;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class CaseManagementActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_casemanagement);

        LinearLayout layout = findViewById(R.id.container_layout);

        SharedPreferences sharedPreferences = getSharedPreferences("my_preferences", Context.MODE_PRIVATE);
        String phoneNumber = sharedPreferences.getString("user", "Default");

        if (phoneNumber != null) {
            new FetchMedicalRecordsTask().execute(phoneNumber);
        } else {
            Toast.makeText(this, "未找到电话号码", Toast.LENGTH_SHORT).show();
        }

        ImageView imageView_arrow = findViewById(R.id.imageView_arrow);
        imageView_arrow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @SuppressLint("StaticFieldLeak")
    private class FetchMedicalRecordsTask extends AsyncTask<String, Void, List<List<Object>>> {

        @Override
        protected List<List<Object>> doInBackground(String... phoneNumbers) {
            String phoneNumber = phoneNumbers[0];
            return MedicalRecordFetcher.getMedicalRecords(phoneNumber);
        }

        @Override
        protected void onPostExecute(List<List<Object>> medicalRecords) {
            super.onPostExecute(medicalRecords);
            if (medicalRecords != null) {
                try {
                    updateUI(medicalRecords);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            } else {
                Toast.makeText(CaseManagementActivity.this, "未获取到医疗记录", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @SuppressLint("SetTextI18n")
    private void updateUI(List<List<Object>> medicalRecords) throws ParseException {
        LinearLayout layout = findViewById(R.id.container_layout);
        LayoutInflater inflater = LayoutInflater.from(this);

        if (layout == null || inflater == null) {
            Toast.makeText(this, "布局或布局填充器为空", Toast.LENGTH_SHORT).show();
            return;
        }

        for (List<Object> record : medicalRecords) {
            RelativeLayout relativeLayout = (RelativeLayout) inflater.inflate(R.layout.relative_layout_template, layout, false);

            TextView textViewCaseNumber = relativeLayout.findViewById(R.id.textViewCaseNumber);
            TextView textViewCreationDate = relativeLayout.findViewById(R.id.textViewCreationDate);

            if (textViewCaseNumber == null || textViewCreationDate == null) {
                Toast.makeText(this, "文本视图为空", Toast.LENGTH_SHORT).show();
                continue;
            }

            @SuppressLint("SimpleDateFormat") SimpleDateFormat originalFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
            @SuppressLint("SimpleDateFormat") SimpleDateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd");
            String formattedDate = null;

            try {
                formattedDate = targetFormat.format(originalFormat.parse((String) record.get(1)));
            } catch (ParseException e) {
                e.printStackTrace();
            }

            @SuppressLint("DefaultLocale") String formattedNumber = String.format("%06d", (int) record.get(0));
            String symptom = (String) record.get(2);
            String prescription = (String) record.get(3);
            String usage = (String) record.get(5);

            textViewCaseNumber.setText("病历(#" + formattedNumber + ")");
            textViewCreationDate.setText("");

            relativeLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showRecordDetailsDialog(symptom, prescription, usage);
                }
            });

            layout.addView(relativeLayout);
        }
    }

    private void showRecordDetailsDialog(String symptom, String prescription, String usage) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_layout, null);

        TextView textViewSymptoms = dialogView.findViewById(R.id.textViewSymptoms);
        TextView textViewPrescription = dialogView.findViewById(R.id.textViewPrescription);
        TextView textViewCreationTime = dialogView.findViewById(R.id.textViewCreationTime);

        textViewSymptoms.setText("症状：" + symptom);
        textViewPrescription.setText("中药处方：" + prescription);
        textViewCreationTime.setText("服用方式：" + usage);

        builder.setView(dialogView)
                .setTitle("病历详情")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        AlertDialog dialog = builder.create();
        dialog.show();
    }
}
